package zl.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class DynamicProxy {
	 
	@SuppressWarnings("unchecked")
	public static void main(String[] args){
		List<Integer> list = (List<Integer>)Proxy.newProxyInstance(ArrayList.class.getClassLoader(), ArrayList.class.getInterfaces(), 
				new InvocationHandler(){
			private ArrayList<Integer> list = new ArrayList<Integer>();
			
			public Object invoke(Object proxy, Method method, Object[] args)throws Throwable{
				long start = System.currentTimeMillis();
				Object obj = method.invoke(list, args);
				TimeUnit.SECONDS.sleep(1);
				System.out.println("["+method.getName()+"] speed："+TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()-start)+"s");
				return obj;
			}
		});
		list.add(1);
		list.add(2);
		list.add(4);
		list.add(7);
		list.add(6);
		list.add(9);
		list.add(3);
		System.out.println("包含1？"+list.contains(1));
		for(Iterator<Integer> i = list.iterator();i.hasNext();){
			if(i.next()%2==0) i.remove();
		}
		/*for(Integer i : list){
			if(i%2==0) list.remove(i); //会出现并发修改异常 java.util.ConcurrentModificationException
		}*/
		for(Iterator<Integer> i = list.iterator();i.hasNext();){
			System.out.println("遍历:"+i.next());
		}
	}

}
